//
//  ZHRequestManager.m
//  ZHS_UCDemo
//
//  Created by Emrys on 2016/11/8.
//  Copyright © 2016年 Emrys. All rights reserved.
//

#import "ZHRequestManager.h"

#import "AFNetworking.h"

#import "ZHTools.h"

#import "ZHS_UC_API.h"

typedef void(^downloadProgress)(NSProgress *downloadProgress);

static const NSString *kZHToken = @"token";
static const NSString *kZHClientType = @"clientType";
static const NSString *kZHIOSClientType = @"iOS";
static const NSString *kZHWebClientType = @"web";

@interface ZHRequestManager ()

@property(nonatomic, strong) AFHTTPSessionManager *httpSessionManager;

@end

@implementation ZHRequestManager

+ (instancetype)sharedManager {
    static id _instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
//        _instance.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    });
    return _instance;
}

- (void)request:(NSString *)urlString
     httpMethod:(ZHHttpMethod)httpMethod
     parameters:(NSDictionary *)parameters
         handle:(handle)handle {
    
    [self request:urlString
          isLogin:NO
       httpMethod:httpMethod
       parameters:parameters
         progress:nil
           handle:handle];
}

- (void)loginRequest:(NSString *)urlString
          httpMethod:(ZHHttpMethod)httpMethod
          parameters:(NSDictionary *)parameters
              handle:(handle)handle {
    
    [self request:urlString
          isLogin:YES
       httpMethod:httpMethod
       parameters:parameters
         progress:nil
           handle:handle];
}

- (void)request:(NSString *)urlString
        isLogin:(BOOL)isLogin
     httpMethod:(ZHHttpMethod)httpMethod
     parameters:(NSDictionary *)parameters
       progress:(downloadProgress)downloadProgress
         handle:(handle)handle {
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@", kZHS_APIHOST_PLAYER, urlString];
    
    NSMutableDictionary *parametersTmp = [NSMutableDictionary dictionaryWithDictionary:parameters];
    
    if (!isLogin) {
        [parametersTmp setObject:[self getToken] forKey:kZHToken];
    }
    
    if ([ZHTools isDemo]) {
        [parametersTmp setObject:kZHWebClientType forKey:kZHClientType];
    } else {
        [parametersTmp setObject:kZHIOSClientType forKey:kZHClientType];
    }
    
    NSDictionary *param = [NSDictionary dictionaryWithDictionary:parametersTmp];
    
    void (^success)(NSURLSessionDataTask *, id) = ^(NSURLSessionDataTask *task, id responseObject) {
        
//        NSString *html = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
//        NSData* data = [html dataUsingEncoding:NSUTF8StringEncoding];
//        id resultObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//        
//        [self storeUpToken:[resultObject objectForKey:kZHToken]];
//        
//        handle(resultObject, nil);
        [self storeUpToken:[responseObject objectForKey:kZHToken]];
        handle(responseObject, nil);
    };
    void (^failure)(NSURLSessionDataTask *, NSError *) = ^(NSURLSessionDataTask *task, NSError *error) {
        handle(nil, error);
    };
    
    switch (httpMethod) {
        case ZH_GET:
            [self.httpSessionManager GET:urlStr
                              parameters:param
                                progress:downloadProgress
                                 success:success
                                 failure:failure];
            break;
        case ZH_POST:
            [self.httpSessionManager POST:urlStr
                               parameters:param
                                 progress:downloadProgress
                                  success:success
                                  failure:failure];
            break;
        default:
            break;
    }
}

#pragma mark - active
- (BOOL)storeUpToken:(NSString *)token {
    [[NSUserDefaults standardUserDefaults] setObject:token forKey:(NSString *)kZHToken];
    return [[NSUserDefaults standardUserDefaults] synchronize];
}
- (NSString *)getToken {
    return [[NSUserDefaults standardUserDefaults] objectForKey:(NSString *)kZHToken];
}

#pragma mark - property
-(AFHTTPSessionManager *)httpSessionManager{
    
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        [AFHTTPSessionManager manager].responseSerializer.acceptableContentTypes =[NSSet setWithObject:@"text/html"];
//
//    });
    
    if (nil == _httpSessionManager) {
        _httpSessionManager = [AFHTTPSessionManager manager];
        _httpSessionManager.responseSerializer.acceptableContentTypes =[NSSet setWithObject:@"text/html"];
    }
    
    return _httpSessionManager;
}

@end
